// 获取搜索框和候选项列表
const searchInput = document.getElementById('searchInput');
const suggestionsList = document.getElementById('suggestions');

// 防抖函数：用户停止输入 300ms 后再发送请求
let debounceTimeout;

function debounce(callback, delay) {
    return function () {
        clearTimeout(debounceTimeout);
        debounceTimeout = setTimeout(() => {
            callback.apply(this, arguments);
        }, delay);
    };
}

// 发送搜索请求的函数
async function fetchSuggestions(query) {
    if (query.trim() === '') {
        suggestionsList.style.display = 'none';
        suggestionsList.innerHTML = '';
        return;
    }

    try {
        const response = await fetch('/search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ key: query })  // 使用 "key" 作为查询参数
        });

        if (!response.ok) {
            throw new Error('网络响应失败');
        }

        const data = await response.json();

        // 显示候选项列表
        suggestionsList.style.display = 'block';
        suggestionsList.innerHTML = ''; // 清空之前的候选项

        data.suggestions.forEach(suggestion => {
            const li = document.createElement('li');
            li.textContent = suggestion;
            li.addEventListener('click', () => {
                searchInput.value = suggestion;
                suggestionsList.style.display = 'none';
            });
            suggestionsList.appendChild(li);
        });
    } catch (error) {
        console.error('搜索请求失败:', error);
    }
}

// 监听输入事件，使用防抖机制
searchInput.addEventListener('input', debounce(function () {
    const query = this.value;
    fetchSuggestions(query);
}, 300));

// 当点击页面其他地方时，隐藏候选项列表
document.addEventListener('click', function (event) {
    if (!suggestionsList.contains(event.target) && event.target !== searchInput) {
        suggestionsList.style.display = 'none';
    }
});

// 当点击搜索框时，显示候选项列表（如果有）
searchInput.addEventListener('focus', function () {
    if (this.value) {
        fetchSuggestions(this.value);
    }
});